package com.heima.wemedia.service.impl;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.ListUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmSensitiveDto;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmSensitiveExcel;

import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.service.WmSensitiveService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;


import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author 22904
 * @description 针对表【wm_sensitive(敏感词信息表)】的数据库操作Service实现
 * @createDate 2024-11-26 21:27:19
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class WmSensitiveServiceImpl extends ServiceImpl<WmSensitiveMapper, WmSensitive>
        implements WmSensitiveService {
    private static final String SENSITIVE_WORDS_KEY = "sensitiveWords";
    private final RedisTemplate<String, Object> redisTemplate;


    @Override
    public ResponseResult deleteById(Integer id) {
        getBaseMapper().deleteById(id);

        // 删除缓存
        Object o = redisTemplate.opsForValue().get(SENSITIVE_WORDS_KEY);
        List<WmSensitive> wmSensitives = (List<WmSensitive>) o;
        if (CollectionUtils.isEmpty(wmSensitives)) {
            wmSensitives.removeIf(wmSensitive -> wmSensitive.getId().equals(id));
            redisTemplate.opsForValue().set(SENSITIVE_WORDS_KEY, wmSensitives);
        }
        return ResponseResult.okResult(null);
    }

    @Override
    public ResponseResult findAll(WmSensitiveDto dto) {
        dto.checkParam();
        Page page = new Page(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmSensitive> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(!StringUtils.isEmpty(dto.getName()), WmSensitive::getSensitives, dto.getName());
        queryWrapper.orderByDesc(WmSensitive::getCreatedTime);
        page = page(page, queryWrapper);
        ResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        result.setData(page.getRecords());
        log.info("查询敏感词成功:{}", result);
        return result;
    }

    @Override
    public ResponseResult saveSensitive(WmSensitive sensitives) {
        LambdaQueryWrapper<WmSensitive> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmSensitive::getSensitives, sensitives.getSensitives());
        List<WmSensitive> wmSensitives = getBaseMapper().selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(wmSensitives)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "敏感词已存在");
        }
        sensitives.setCreatedTime(new Date());
        getBaseMapper().insert(sensitives);
        // 缓存敏感词
        Object o = redisTemplate.opsForValue().get(SENSITIVE_WORDS_KEY);
        List<WmSensitive> sensitiveWords = (List<WmSensitive>) o;
        if (CollectionUtils.isEmpty(sensitiveWords)) {
            sensitiveWords = getBaseMapper().selectList(null);
            redisTemplate.opsForValue().set(SENSITIVE_WORDS_KEY, sensitiveWords);
        } else {
            sensitiveWords.add(sensitives);
            redisTemplate.opsForValue().set(SENSITIVE_WORDS_KEY, sensitiveWords);
        }
        return ResponseResult.okResult(null);

    }

    @Override
    public ResponseResult updateSensitive(WmSensitive sensitives) {
        LambdaQueryWrapper<WmSensitive> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmSensitive::getSensitives, sensitives.getSensitives());
        List<WmSensitive> wmSensitives = getBaseMapper().selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(wmSensitives)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "敏感词已存在");
        }
        getBaseMapper().updateById(sensitives);

        // 缓存敏感词
        Object o = redisTemplate.opsForValue().get(SENSITIVE_WORDS_KEY);
        List<WmSensitive> sensitiveWords = (List<WmSensitive>) o;
        if (CollectionUtils.isEmpty(sensitiveWords)) {
            sensitiveWords = getBaseMapper().selectList(null);
            redisTemplate.opsForValue().set(SENSITIVE_WORDS_KEY, sensitiveWords);
        } else {
            sensitiveWords.removeIf(wmSensitive -> wmSensitive.getId().equals(sensitives.getId()));
            sensitiveWords.add(sensitives);
            redisTemplate.opsForValue().set(SENSITIVE_WORDS_KEY, sensitiveWords);
        }
        return ResponseResult.okResult(null);
    }

    @Override
    public void export() {
        String fileName = "C:\\Users\\tp\\Desktop\\abc.xlsx";
//        // 导出敏感词"Id","敏感词", "创建时间"
        List<String> header = new ArrayList<>();
        header.add("Id");
        header.add("敏感词");
        header.add("创建时间");
        List<List<String>> data = new ArrayList<>();
        data.add(header);
        List<WmSensitive> wmSensitives = getBaseMapper().selectList(null);
        SimpleDateFormat simleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        AtomicInteger index = new AtomicInteger(1);
        wmSensitives.forEach(wmSensitive -> {
            List<String> row = new ArrayList<>();
            row.add(String.valueOf(index.getAndIncrement()));
            row.add(wmSensitive.getSensitives());
            //转化时间为时间格式为yyyy-MM-dd HH:mm:ss
            if (wmSensitive.getCreatedTime() != null) {
                row.add(simleDateFormat.format(wmSensitive.getCreatedTime()));
            }
            data.add(row);
        });
        EasyExcel.write(fileName).sheet("Sheet1").doWrite(data);


    }

    @Override
    public void importExcel(MultipartFile file) {
        try {
            List<WmSensitiveExcel> list = EasyExcel.read(file.getInputStream())
                    .head(WmSensitiveExcel.class)
                    .sheet()
                    .doReadSync();
            if (CollectionUtils.isEmpty(list)) {
                log.warn("导入的敏感词列表为空");
                return; // 或者根据业务需求返回相应的结果
            }

            // 先将数据库中存在的敏感词加载到一个集合中，避免重复查询
            List<WmSensitive> existingSensitives = getBaseMapper().selectList(null);
            Set<String> existingSensitiveSet = existingSensitives.stream()
                    .map(WmSensitive::getSensitives)
                    .collect(Collectors.toSet());

            // 插入到数据库,重复不插
            for (WmSensitiveExcel s : list) {
                if (!existingSensitiveSet.contains(s.getSensitives())) {
                    WmSensitive wmSensitive = new WmSensitive();
                    wmSensitive.setSensitives(s.getSensitives());
                    wmSensitive.setCreatedTime(new Date());
                    getBaseMapper().insert(wmSensitive);
                }
            }
        } catch (IOException e) {
            log.error("导入敏感词时发生错误: {}", e.getMessage());
            throw new RuntimeException("文件读取失败", e); // 提供更多上下文信息
        }


    }


}




